package fr.generali.accueilclient.gwt.client.editor;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.InsertPanel;
import com.google.gwt.user.client.ui.RadioButton;

public class EnumRadioButtonEditor<E extends Enum<?>> implements LeafValueEditor<E> {

    private Map<RadioButton, E> map;
    
    private final InsertPanel panel;
    
    @UiConstructor
    public EnumRadioButtonEditor(String groupName, Class<E> clazz, InsertPanel panel) {
        map = new HashMap<RadioButton, E>();
        this.panel = panel;
        
        for (E e: clazz.getEnumConstants()){
            RadioButton rb = new RadioButton(groupName, e.name());
            map.put(rb, e);
            this.panel.add(rb);
        }
    }

    @Override
    public void setValue(E value) {
        if (value==null)
            return;
        RadioButton radioBtn = (RadioButton) panel.getWidget(value.ordinal());
        radioBtn.setValue(true);
    }

    @Override
    public E getValue() {
        for (Entry<RadioButton, E> e: map.entrySet()) {
            if (e.getKey().getValue())
                return e.getValue();
        }
        return null;
    }
}